package com.rockcent.mall.lib.repository;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.SQLObjectDoing;
import com.rockcent.mall.lib.dto.LocationDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * Created by zhangjh on 2016/10/24.
 */
@Repository
public class LocationRepositoryImpl implements LocationRepositoryCustom{
    private static final Logger log = LoggerFactory.getLogger(LocationRepositoryImpl.class);
    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    public LocationDto findLongLocation(Long locationId){
        SQLObjectDoing<LocationDto> doing = (sql, fields, params, typeReferenceMap) -> {
            sql.append("SELECT CONCAT(IFNULL(a.location_name,\"\"),IFNULL(b.location_name,\"\")) AS locationName FROM  ");
            sql.append(" (SELECT CONCAT(IFNULL(lo.location_name,\"\"),IFNULL(l.location_name,\"\")) AS location_name,lo.parent_id,l.id FROM location l LEFT JOIN location lo ON lo.id = l.parent_id WHERE l.id = :locationId) b LEFT JOIN  location a  ");
            sql.append(" ON a.id = b.parent_id ");
            params.put("locationId",locationId);
        };
        return doing.go( LocationDto.class , jdbcTemplate, log, objectMapper);
    }
}
